﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.Model;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Common;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class PublicSecurityViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IPublicSecurityService publicSecurityService = ServiceFactory.CreateService<IPublicSecurityService>();
            IPublicSecurityPersonService publicSecurityPersonService = ServiceFactory.CreateService<IPublicSecurityPersonService>();

            ConditionGroup group = new ConditionGroup();
            int totalCount = 0;
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    IPublicSecurity publicSecurity = (IPublicSecurity)JsonToEntity<PublicSecurity>(RepairString(data));
                    bool isSendMsg = !string.IsNullOrEmpty(publicSecurity.IsSendMsg);
                    GetLeaders(publicSecurity, isSendMsg);
                    if (publicSecurity.Id == 0)
                    {
                        publicSecurity.Enable = true;
                        if (LoginEmployee != null)
                        {
                            publicSecurity.Writer = LoginEmployee;
                            publicSecurity.CreateDate = DateTime.Now;
                            publicSecurityService.Create(publicSecurity);
                            ReturnSuccessMessage("保存治安要情成功");
                        }
                        else
                        { ReturnErrorMessage("未登陆或数字证书已过期！"); }
                    }
                    else
                    {
                        IPublicSecurity OldPublicSecurity = publicSecurityService.Get(publicSecurity.Id);
                        OldPublicSecurity.ModifyDate = DateTime.Now;
                        OldPublicSecurity.Title = publicSecurity.Title;
                        OldPublicSecurity.Content = publicSecurity.Content;
                        OldPublicSecurity.Persons = publicSecurity.Persons;
                        publicSecurityService.Update(OldPublicSecurity);
                        ReturnSuccessMessage("更新治安要情成功");
                    }
                    break;
                case "Search":
                    Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    group.Conditions.Add(enableCondition);
                    IList<Sort> sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                    IList<IPublicSecurity> publicSecurityList = publicSecurityService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    var obj = from n in publicSecurityList
                              select new
                              {
                                  Id = n.Id,
                                  Title = n.Title,
                                  Content = n.Content,
                                  Writer = n.Writer == null ? "" : n.Writer.Name,
                                  Leaders = string.Join(",", (from p in n.Persons
                                                              where p.Enable == true
                                                              select p.Name).ToArray()),
                                  Unread = GetLeadersStatus(n.Id),
                                  CreateDate = n.CreateDate.ToString()
                              };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    publicSecurity = JsonToEntity<PublicSecurity>(Searchjson);
                    enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    Condition condition1 = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = '%' + publicSecurity.Name + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                    group.Conditions.Add(enableCondition);
                    group.Conditions.Add(condition1);
                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                     publicSecurityList = publicSecurityService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    obj = from n in publicSecurityList
                          select new
                          {
                              Id = n.Id,
                              Title = n.Title,
                              Content = n.Content,
                              Writer = n.Writer == null ? "" : n.Writer.Name,
                              Leaders = string.Join(",", (from p in n.Persons
                                                          where p.Enable == true
                                                          select p.Name).ToArray()),
                              Unread = GetLeadersStatus(n.Id),
                              CreateDate = n.CreateDate.ToString()

                          };
                    var objList = obj.ToList();
                    ReturnList(objList.Count, objList);
                    break;
                case "Get":
                    publicSecurity = publicSecurityService.Get(Id);
                    object objPublicSecurity = (new
                                     {
                                         Id = publicSecurity.Id,
                                         Title = publicSecurity.Title,
                                         Content = publicSecurity.Content
                                     });
                    ReturnObj(objPublicSecurity);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的治安要情ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    publicSecurityService.Delete(idList);
                    ReturnSuccessMessage("删除治安要情成功");
                    break;
                case "GetLeadersByPublicSecurityId":
                    IPublicSecurity ps = publicSecurityService.Get(Id);
                    string leaders = string.Join(",", (from p in ps.Persons
                                                       where p.Enable = true
                                                       select p.Code.ToString()).ToArray<string>());
                    ReturnSuccessMessage(leaders);
                    break;
            }
        }
        private string GetLeadersStatus(int Id)
        {
            int totalCount = 0;
            IPublicSecurityPersonService publicSecurityPersonService = ServiceFactory.CreateService<IPublicSecurityPersonService>();
            ConditionGroup conditionGroup = new ConditionGroup();
            conditionGroup.Conditions.Add(new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true });
            conditionGroup.Conditions.Add(new Condition() { Type = typeof(int).FullName, Value1 = Id, Field = "PublicSecurity.Id", Relation = Relations.And });
            IList<IPublicSecurityPerson> publicSecurityPersonList = publicSecurityPersonService.Search(conditionGroup, null, Int32.MaxValue, 1, out totalCount);
            string status = string.Join(",", (from m in publicSecurityPersonList
                                              where m.Person != null&&m.Receive==false
                                              select m.Person.Name).ToArray());
            return status;

        }
        private void GetLeaders(IPublicSecurity publicSecurity, bool IsSendMsg)
        {
            string[] codes;
            if (!string.IsNullOrEmpty(Request["Leaders"]))
            {
                codes = Request["Leaders"].Split(',');
                if (codes.Length > 0)
                {
                    publicSecurity.Persons = new List<IEmployee>();
                    foreach (string code in codes)
                    {
                        IEmployeeService service = ServiceFactory.CreateService<IEmployeeService>();
                        IEmployee emp = service.Get(code);
                        if (emp != null)
                        {
                            publicSecurity.Persons.Add(emp);
                            if (IsSendMsg)
                            {
                                string tel = (from c in emp.Contacts
                                              where c.ContactType.Name == "手机"
                                              select c.Value).FirstOrDefault();
                                if (!string.IsNullOrEmpty(tel))
                                {
                                    MessageManager.SendMessage(tel, "您有新的治安要情：" + publicSecurity.Title + ",请通过决策指挥终端查看详情。（发送人：" + LoginEmployee.Name+")", LoginEmployee.Code, DateTime.Now);
                                }

                            }
                        }

                    }
                }
            }
        }
    }
}